package t2.server;

import java.util.concurrent.Callable;

import t2.server.xbee.XBeePort;

import com.rapplogic.xbee.api.AtCommand;
import com.rapplogic.xbee.api.AtCommandResponse;
import com.rapplogic.xbee.api.PacketListener;
import com.rapplogic.xbee.api.XBee;
import com.rapplogic.xbee.api.XBeeResponse;

public class DoNC implements Callable<Integer> {
    boolean responseReceived;
    private Integer numberOfChildren = 0;
    int nop = 0;

    PacketListener NC = new PacketListener() {

        @Override
        public void processResponse(XBeeResponse response) {
            AtCommandResponse atResp = (AtCommandResponse) response;
            if (atResp.getCommand().equals("NC")) {
                setNumberOfChildren(atResp.getValue()[0]);
                responseReceived = true;
            }
        }
    };

    @Override
    public Integer call() throws Exception {
        XBee xbee = XBeePort.getXBeePort().getXbee();
        xbee.addPacketListener(NC);
        xbee.sendAsynchronous(new AtCommand("NC"));
        do {
            Thread.sleep(1);
            nop++;
        }
        while (!responseReceived && nop < 6000);
        xbee.removePacketListener(NC);
        xbee.clearResponseQueue();


        return getNumberOfChildren();
    }

    public int getNumberOfChildren() {
        return numberOfChildren;
    }

    public void setNumberOfChildren(int numberOfChildren) {
        this.numberOfChildren = numberOfChildren;
    }

}
